package com.npave.zryhadapter.config;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.bean.result.WxMpUserList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;

import javax.annotation.PostConstruct;
import java.util.LinkedList;
import java.util.List;

/**
 * @program: cytoderm
 * @description:
 * @author: wj
 * @create: 2022-12-12 14:41
 */
@Slf4j
@AllArgsConstructor
@Configuration
@EnableConfigurationProperties(WxMpProperties.class)
public class WxMpInitConfiguration {
    private final WxMpProperties properties;

    @Autowired
    private WxMpService wxMpService;
//    @Autowired
//    private ApiUserService apiUserService;
//    @Autowired
//    private UserAccountService userAccountService;

    /**
     * 同步公众号用户信息
     * @throws WxErrorException
     */
    @PostConstruct
    @Async
    public void init() throws WxErrorException {
        for (WxMpProperties.MpConfig config : properties.getConfigs()) {
            if(config.getSyncUser() != null && config.getSyncUser()){
                log.info(StrUtil.format("开始同步:{}用户信息!",config.getAppId()));
                List<String> openIdList = new LinkedList<>();
                String nextOpenId = null;
                WxMpService wxMpService = this.wxMpService.switchoverTo(config.getAppId());
                do {
                    WxMpUserList wxMpUserList = wxMpService.getUserService().userList(nextOpenId);
                    openIdList.addAll(wxMpUserList.getOpenids());
                    nextOpenId = wxMpUserList.getNextOpenid();
                }while (StrUtil.isNotBlank(nextOpenId));
//                List<String> data = userAccountService.listWechatMpOpenid();
//                openIdList =  new LinkedList<>(CollectionUtil.subtract(openIdList,data));
//                List<List<String>> split = ListUtil.split(openIdList, 100);
//                for (List<String> openIds : split) {
//                    List<WxMpUser> wxMpUsers = this.wxMpService.getUserService().userInfoList(openIds);
//                    for (WxMpUser wxMpUser : wxMpUsers) {
//                        String unionId = wxMpUser.getUnionId();
//                        String openId = wxMpUser.getOpenId();
//                        apiUserService.loginByWxMp(openId,unionId);
//                    }
//                }
                log.info(StrUtil.format("同步完成:{}用户信息数量:{}!",config.getAppId(),openIdList));
            }
        }
    }


}
